﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace JPCloudPrinter.Utils {
    public class HttpUtil {
        public delegate void DownloadProgressCallback(long progress,long total);

        public static ContentInfo Head(String url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            request.Method = "HEAD";
            request.Timeout = 5000;

            var response = (HttpWebResponse)request.GetResponse();

            ContentInfo cif = new ContentInfo();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                cif.ContentLength = response.ContentLength;
            }
            
            cif.LastModified = response.LastModified;
            cif.ContentLength = response.ContentLength;

            response.Close();

            return cif;
        }

        public static void Download(string url,string filePath,DownloadProgressCallback callback)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            request.Method = "GET";
            request.Timeout = 10000;

            var response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream from = response.GetResponseStream();

                FileStream to = new FileStream(filePath,FileMode.Create,FileAccess.Write);

                byte[] buffer = new byte[4098];

                int len = 0;
                long contentLength = response.ContentLength;
                long progress = 0;

                while ((len=from.Read(buffer, 0,buffer.Length))>0)
                {
                    to.Write(buffer, 0, len);

                    progress += len;

                    callback(progress,contentLength);
                }

                response.Close();
                to.Close();
            }
        }
    }

    public class ContentInfo {
        public DateTime LastModified{get;set;}
        public long ContentLength{get;set;}
    }
}
